package com.nearby.demand.ui;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.auto.layout.lib.AutoLayoutActivity;
import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.util.VoiceRecorder;
import com.nearby.demand.R;
import com.nearby.demand.adapter.MessageAdapter;
import com.nearby.demand.adapter.listener.OnItemClickListener;
import com.nearby.demand.ui.view.ChatView;
import com.nearby.demand.utils.KLog;
import com.nearby.demand.utils.ToolUtils;
import com.nearby.demand.voice.VoicePlayClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.OnTouch;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by IME on 2016/home_1/13.
 */
public class UiChat extends AutoLayoutActivity implements ChatView, EMEventListener {


    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.chat_recycler_view)
    RecyclerView chatRecyclerView;
    @Bind(R.id.chat_ptr_class_frame)
    PtrClassicFrameLayout chatPtrClassFrame;
    @Bind(R.id.btn_send)
    Button btnSend;
    @Bind(R.id.btn_more)
    Button btnMore;
    @Bind(R.id.btn_press_to_speak)
    LinearLayout btnPressToSpeak;
    @Bind(R.id.mic_image)
    ImageView micImage;
    @Bind(R.id.view_talk)
    LinearLayout recordingContainer;
    @Bind(R.id.recording_hint)
    TextView recordingHint;
    @Bind(R.id.btn_set_mode_voice)
    Button btn_set_mode_voice;
    @Bind(R.id.btn_set_mode_keyboard)
    Button btn_set_mode_keyboard;
    @Bind(R.id.edittext_layout)
    RelativeLayout edittext_layout;
    @Bind(R.id.more)
    LinearLayout more;
    @Bind(R.id.iv_emoticons_normal)
    ImageView iv_emoticons_normal;
    @Bind(R.id.iv_emoticons_checked)
    ImageView iv_emoticons_checked;
    @Bind(R.id.ll_btn_container)
    LinearLayout ll_btn_container;
    @Bind(R.id.ll_face_container)
    LinearLayout ll_face_container;


    private EMConversation conversation;
    private String toChatUsername;
    private MessageAdapter adapter;
    private List<EMMessage> messages = new ArrayList<EMMessage>();
    AnimationDrawable animationDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_chat, 1);
        toChatUsername = getIntent().getStringExtra("toChatUsername");
        KLog.i("toChatUsername=" + toChatUsername);
        conversation = EMChatManager.getInstance().getConversation(
                toChatUsername);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//禁止进入弹出软键盘
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
        ButterKnife.bind(this);

        initRe();
    }

    @Override
    public void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        //        toolbar.showOverflowMenu();
        toolbar.hideOverflowMenu();
        View view = getLayoutInflater().inflate(R.layout.toolbar_button_is_toolbar, toolbar);
        TextView textView = (TextView) view.findViewById(R.id.toolbar_title);
        textView.setText("聊天sss");


    }

    private Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
        }
    };
    private VoiceRecorder voiceRecorder;

    public void initRe() {
        animationDrawable = (AnimationDrawable) micImage.getBackground();
        animationDrawable.setOneShot(false);
        //语音发送
        voiceRecorder = new VoiceRecorder(micImageHandler);

        chatPtrClassFrame.setLastUpdateTimeRelateObject(this);
        chatPtrClassFrame.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub 5
                chatPtrClassFrame.refreshComplete();
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                chatPtrClassFrame.refreshComplete();
            }

        });
        // the following are default settings
        chatPtrClassFrame.setResistance(1.7f);
        chatPtrClassFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        chatPtrClassFrame.setDurationToClose(200);
        chatPtrClassFrame.setDurationToCloseHeader(1000);
        // default is false
        chatPtrClassFrame.setPullToRefresh(false);
        // default is true
        chatPtrClassFrame.setKeepHeaderWhenRefresh(true);

        chatRecyclerView.setHasFixedSize(true);//固定尺寸
        linearLayoutManager = new LinearLayoutManager(UiChat.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //        linearLayoutManager.setReverseLayout(true);
        chatRecyclerView.setLayoutManager(linearLayoutManager);
        adapter = new MessageAdapter(messages, toChatUsername, this);
        adapter.setActivity(this);
        // 显示消息
        chatRecyclerView.setAdapter(adapter);
        initListViewCreation();
    }

    LinearLayoutManager linearLayoutManager;


    public void initListViewCreation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // UI线程不能直接使用conversation.getAllMessages()
                // 否则在UI刷新过程中，如果收到新的消息，会导致并发问题
                EMConversation conversations = EMChatManager.getInstance().getConversation(toChatUsername);
                messages = conversations.getAllMessages();
                KLog.i("messages.size=" + messages.size());
                adapter.addList(messages);
                //                adapter.notifyDataSetChanged();

            }
        }).start();
        adapter.setOnItemClickListener(new OnItemClickListener<EMMessage>() {

            @Override
            public void onClick(View view, EMMessage message) {
                Toast.makeText(UiChat.this, "短" + message.getMsgId(), Toast.LENGTH_SHORT).show();

            }
        });
    }

    public String getToChatUsername() {
        return toChatUsername;//转换成小写
    }

    @Override
    protected void onResume() {
        super.onResume();
        // register the event listener when enter the foreground
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage,
                        EMNotifierEvent.Event.EventDeliveryAck, EMNotifierEvent.Event.EventReadAck});
    }

    private void refreshUIWithNewMessage() {
        if (adapter == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            public void run() {
                EMConversation conversations = EMChatManager.getInstance().getConversation(toChatUsername);
                messages = conversations.getAllMessages();
                adapter.addList(messages);
                chatRecyclerView.smoothScrollToPosition(adapter.getItemCount());
                //                moveToPosition(messages.size()-home_1);
            }
        });
    }

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            chatRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = chatRecyclerView.getChildAt(n - firstItem).getTop();
            chatRecyclerView.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            chatRecyclerView.scrollToPosition(n);
        }

    }

    /**
     * 事件监听
     * <p>
     * see {@link EMNotifierEvent}
     */
    @Override
    public void onEvent(EMNotifierEvent event) {
        KLog.i("onEvent chat. laile");
        switch (event.getEvent()) {
            case EventNewMessage: {
                //获取到message
                EMMessage message = (EMMessage) event.getData();
                String username = null;
                //群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    //单聊消息
                    username = message.getFrom();
                }
                //                Log.i("G3-log", username + "--" + getToChatUsername());
                //如果是当前会话的消息，刷新聊天页面
                if (username.equals(getToChatUsername())) {//获取小写
                    //                    KLog.i(" //如果是当前会话的消息，刷新聊天页面");
                    refreshUIWithNewMessage();
                    //                   //刷新界面滚动到底部
                    //声音和震动提示有新消息
                } else {
                    //如果消息不是和当前聊天ID的消息//发送通知
                }

                break;
            }
            case EventDeliveryAck: {
                //获取到message
                EMMessage message = (EMMessage) event.getData();
                //                refreshUI();
                break;
            }
            case EventReadAck: {
                //获取到message
                EMMessage message = (EMMessage) event.getData();
                //                refreshUI();
                break;
            }
            case EventOfflineMessage: {
                //a list of offline messages
                //List<EMMessage> offlineMessages = (List<EMMessage>) event.getData();
                //                refreshUI();
                break;
            }
            default:
                break;
        }

    }

    @Override
    public void sendText() {
        String content = etContent.getText().toString().trim();
        if (content.length() > 0) {
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            TextMessageBody txtBody = new TextMessageBody(content);
            // 设置消息body
            message.addBody(txtBody);
            // 设置要发给谁,用户username或者群聊groupid
            message.setReceipt(toChatUsername);
            // 把messgage加到conversation中
            conversation.addMessage(message);
            // 通知adapter有消息变动，adapter会根据加入的这条message显示消息和调用sdk的发送方法
            //            adapter.refresh();
            //            listView.setSelection(listView.getCount() - home_1);
            etContent.setText("");
            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    KLog.i("onSuccess");
                    chatRecyclerView.smoothScrollToPosition(adapter.getItemCount());
                }

                @Override
                public void onError(int i, String s) {
                    KLog.i("onError");
                }

                @Override
                public void onProgress(int i, String s) {
                    KLog.i("onProgress");
                }
            });

        }

    }

    private InputMethodManager manager;

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @OnClick(R.id.btn_send)
    public void sendMessage() {
        sendText();
    }

    @OnTextChanged(value = R.id.et_content, callback = OnTextChanged.Callback.TEXT_CHANGED)
    public void onTextChanged(CharSequence s, int start, int before,
                              int count) {
        if (!TextUtils.isEmpty(s)) {
            btnMore.setVisibility(View.GONE);
            btnSend.setVisibility(View.VISIBLE);
        } else {
            btnMore.setVisibility(View.VISIBLE);
            btnSend.setVisibility(View.GONE);
        }
    }

    /**语音*/
    @OnClick(R.id.btn_set_mode_voice)
    public void modeVoice() {
        hideKeyboard();
        edittext_layout.setVisibility(View.GONE);//输入框
        more.setVisibility(View.GONE);//更多
        btnSend.setVisibility(View.GONE);//发送
        btnPressToSpeak.setVisibility(View.VISIBLE);//语音按住发送
        btn_set_mode_voice.setVisibility(View.GONE);//语音按钮
        btn_set_mode_keyboard.setVisibility(View.VISIBLE);//键盘按钮
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        ll_btn_container.setVisibility(View.INVISIBLE);//图片位置文件
        ll_face_container.setVisibility(View.GONE);//表情图片
    }

    /**键盘*/
    @OnClick(R.id.btn_set_mode_keyboard)
    public void modeKeyBoard() {
        edittext_layout.setVisibility(View.VISIBLE);//输入框
        more.setVisibility(View.GONE);//更多
        btn_set_mode_keyboard.setVisibility(View.GONE);
        btn_set_mode_voice.setVisibility(View.VISIBLE);
        etContent.requestFocus();
        btnPressToSpeak.setVisibility(View.GONE);//语音按住发送
        if (TextUtils.isEmpty(etContent.getText())) {
            btnMore.setVisibility(View.VISIBLE);
            btnSend.setVisibility(View.GONE);
        } else {
            btnMore.setVisibility(View.GONE);
            btnSend.setVisibility(View.VISIBLE);
        }
    }

    /**更多*/
    @OnClick(R.id.btn_more)
    public void more() {
        if (more.getVisibility() == View.GONE) {
            hideKeyboard();
            more.setVisibility(View.VISIBLE);
            ll_btn_container.setVisibility(View.VISIBLE);//图片位置文件
            ll_face_container.setVisibility(View.GONE);//表情图片
        }else {
            if(ll_face_container.getVisibility()==View.VISIBLE) {
                ll_face_container.setVisibility(View.GONE);
                ll_btn_container.setVisibility(View.VISIBLE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
            } else {
                more.setVisibility(View.GONE);
            }
        }

    }

    public String playMsgId;
    private PowerManager.WakeLock wakeLock;

    @OnTouch(R.id.btn_press_to_speak)
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                animationDrawable.start();
                if (!ToolUtils.isExitsSdcard()) {
                    Toast.makeText(UiChat.this, "发送语音需要sdcard支持", Toast.LENGTH_SHORT)
                            .show();
                    return false;
                }
                try {
                    v.setPressed(true);
                    //                    屏幕将停留在设定的状态，一般为亮、暗状态
                    wakeLock.acquire();
                    if (VoicePlayClickListener.isPlaying)
                        VoicePlayClickListener.currentPlayListener
                                .stopPlayVoice();
                    recordingContainer.setVisibility(View.VISIBLE);
                    recordingHint
                            .setText("手指上滑，取消发送");
                    recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    voiceRecorder.startRecording(null, toChatUsername,
                            getApplicationContext());
                } catch (Exception e) {
                    e.printStackTrace();
                    v.setPressed(false);
                    if (wakeLock.isHeld())
                        //                        释放掉正在运行的cpu或关闭屏幕。
                        wakeLock.release();
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    recordingContainer.setVisibility(View.INVISIBLE);
                    Toast.makeText(UiChat.this, "录音失败，请重试！",
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
            case MotionEvent.ACTION_MOVE: {
                if (event.getY() < 0) {
                    recordingHint
                            .setText("松开手指，取消发送");
                    recordingHint
                            .setBackgroundResource(R.drawable.recording_text_hint_bg);
                } else {
                    recordingHint
                            .setText("手指上滑，取消发送");
                    recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    animationDrawable.start();
                }
                return true;
            }
            case MotionEvent.ACTION_UP:
                if (animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                v.setPressed(false);
                recordingContainer.setVisibility(View.INVISIBLE);
                if (wakeLock.isHeld())
                    wakeLock.release();
                if (event.getY() < 0) {
                    // discard the recorded audio.
                    voiceRecorder.discardRecording();

                } else {
                    // stop recording and send voice file
                    try {
                        int length = voiceRecorder.stopRecoding();
                        if (length > 0) {
                            sendVoice(voiceRecorder.getVoiceFilePath(),
                                    voiceRecorder
                                            .getVoiceFileName(toChatUsername),
                                    Integer.toString(length), false);
                        } else if (length == EMError.INVALID_FILE) {
                            Toast.makeText(getApplicationContext(), "无录音权限",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "录音时间太短",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(UiChat.this, "发送失败，请检测服务器是否连接",
                                Toast.LENGTH_SHORT).show();
                    }
                }
                return true;
            default:
                recordingContainer.setVisibility(View.INVISIBLE);
                if (voiceRecorder != null)
                    voiceRecorder.discardRecording();
                return false;
        }
    }

    /**
     * 发送语音
     *
     * @param filePath
     * @param fileName
     * @param length
     * @param isResend
     */
    private void sendVoice(String filePath, String fileName, String length,
                           boolean isResend) {
        if (!(new File(filePath).exists())) {
            return;
        }
        try {
            final EMMessage message = EMMessage
                    .createSendMessage(EMMessage.Type.VOICE);
            // 如果是群聊，设置chattype,默认是单聊
            //            if (chatType == CHATTYPE_GROUP)
            //                message.setChatType(EMMessage.ChatType.GroupChat);
            message.setReceipt(toChatUsername);
            int len = Integer.parseInt(length);
            VoiceMessageBody body = new VoiceMessageBody(new File(filePath),
                    len);
            message.addBody(body);
            conversation.addMessage(message);
            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    KLog.i("onSuccess");
                    chatRecyclerView.smoothScrollToPosition(adapter.getItemCount());
                }

                @Override
                public void onError(int i, String s) {
                    KLog.i("onError");
                }

                @Override
                public void onProgress(int i, String s) {
                    KLog.i("onProgress");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    @Override
    public void sendPicFromCamera() {

    }

    @Override
    public void sendPicFromPhoto() {

    }

    @Override
    public void sendFile() {

    }

    @Override
    public void sendVideo() {

    }

    @Override
    public void sendAudio() {

    }

    @Override
    public void sendLocation() {

    }
}
